package com.dqp.cslggroup.LostAndFound;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Spannable;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.UI.RoundImageView;
import com.dqp.cslggroup.Util.NoUnderlineSpan;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.student;
import com.dqp.cslggroup.greendao.studentDao;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

public class entry extends BaseActivity {
    private EditText xh, xm, qq;
    private Button up;
    private CheckBox bw;
    private String name, id, qqnu, bwnu = "0", sql_xh, sql_xm;
    private int count = 0, qqcount = 0;
    private String lr_url = "http://47.96.190.22/lostproperty/information.php";
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private RoundImageView head;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entry);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        initCmp();
        initText();
        entry_up();
    }

    private void initCmp() {
        xh = findViewById(R.id.entry_xh);
        xm = findViewById(R.id.entry_name);
        qq = findViewById(R.id.entry_qq);
        bw = findViewById(R.id.entry_bw);
        up = findViewById(R.id.entry_upbnt);
        head = findViewById(R.id.iv_qqhead);
        TextView tishi = findViewById(R.id.entry_tishi);
        tishi.setMovementMethod(LinkMovementMethod.getInstance());
        NoUnderlineSpan mNoUnderlineSpan = new NoUnderlineSpan();
        if (tishi.getText() instanceof Spannable) {
            Spannable s = (Spannable) tishi.getText();
            s.setSpan(mNoUnderlineSpan, 0, s.length(), Spanned.SPAN_MARK_MARK);
        }
    }

    public void entry_up() {
        up.setOnClickListener(view -> {
            id = xh.getText().toString();
            name = xm.getText().toString();
            qqnu = qq.getText().toString();
            if (bw.isChecked())
                bwnu = "1";
            else
                bwnu = "0";
            if (xh.length() < 7 || xh.length() > 10 || xm.length() < 2 || qqnu.length() < 7 || qqnu.length() > 12) {
                ToastUtil.showToast("请务必输入正确信息！");
            } else if (count == 0) {
                ToastUtil.showToast("请先登录教务系统！");
            } else if (id.equals(sql_xh) && name.equals(sql_xm)) {
                luru();
            } else
                ToastUtil.showToast("请使用本人信息录入！");
        });
    }


    @SuppressLint("SetTextI18n")
    private void initText() {
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        student student;
        count = studentList.size();
        if (count > 0) {
            student = studentList.get(0);
            sql_xm = student.getXm();
            sql_xh = student.getXh();
            xh.setText(sql_xh);
            xm.setText(sql_xm);
        } else ToastUtil.showToast("请先登录教务系统！");

    }

    @SuppressLint("HandlerLeak")
    public void luru() {
        new Thread(() -> {
            try {
                Connection.Response response;
                response = Jsoup.connect(lr_url)
                        .ignoreContentType(true) // 获取图片需设置忽略内容类型
                        .userAgent("Mozilla")
                        .data("number", id)
                        .data("name", name)
                        .data("qq", qqnu)
                        .data("bw", bwnu)
                        .method(Connection.Method.POST)
                        .timeout(3000)
                        .execute();
                Document document = Jsoup.parse(response.body());
                if (document.text().contains("修改")) {
                    sp = getSharedPreferences("luru_accept", MODE_PRIVATE);
                    editor = sp.edit();
                    editor.putBoolean("luru_accept", false);
                    editor.apply();
                    EventBus.getDefault().post(new MessageEvent("entry", 2, null));
                } else if (document.text().contains("成功")) {
                    sp = getSharedPreferences("luru_accept", MODE_PRIVATE);
                    editor = sp.edit();
                    editor.putBoolean("luru_accept", false);
                    editor.apply();
                    EventBus.getDefault().post(new MessageEvent("entry", 1, null));
                } else {
                    EventBus.getDefault().post(new MessageEvent("entry", 3, null));
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }

    public void saveQq(String name, String sno, String qq, String bw) {
        student student = MyApplication.getDaoInstant().getStudentDao().queryBuilder()
                .where(studentDao.Properties.Xh.eq(sno))
                .build().unique();
        student.setQq(qq);
        student.setBw(bw);
        MyApplication.getDaoInstant().getStudentDao().update(student);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("entry")) {
            switch (event.getWhat()) {
                case 1:
                    finish();
                    ToastUtil.showToast("信息录入成功！");
                    saveQq(name, id, qqnu, bwnu);
                    break;
                case 2:
                    finish();
                    ToastUtil.showToast("该用户已存在，如果需要修改信息请联系管理员!");
                    break;
                case 3:
                    ToastUtil.showToast("信息录入失败！请联系开发者！");
                    break;
            }
        }
    }

}
